﻿using Microsoft.AspNetCore.Http;
using Mrc.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ServiceCollectionExtensions
    {
        public  static IServiceCollection AddConfigCenter(this IServiceCollection services, Action<MrcConfigOptions> settingpAction)
        {
            services.AddSingleton<ISerializer,MessagesSerializer>();
            var options = new MrcConfigOptions();
            settingpAction(options);
            var provider = new JsonConfigFileProvider(options.ConfigFileInfos.Values.ToList());
            services.AddSingleton<IJsonConfigFileProvider>(provider);
            var kv = new KVConfigStoreCenter(provider.GetAllStreams());
            options.ItemName = kv.Get("ItemName");
            options.MasterHost = kv.Get("MasterHost");
            foreach(var serviceExtension in options.Extensions)
            {
                serviceExtension.AddServices(services);
            }
            services.Configure(settingpAction);
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpClient();
           
            //如果不是主节点则请求主节点获取初始配置
            if(!string.IsNullOrWhiteSpace(options.MasterHost))
            {
                var servicesProvider = services.BuildServiceProvider();
                var httpClientFactory = servicesProvider.GetService<IHttpClientFactory>();                
                new InitConfigManager(httpClientFactory).Init(kv);
            }
            else
            {
                foreach (var item in kv.AllKV)
                {
                    LocationConfigStore.Set(item.Key, item.Value);
                }
            }
            return services;
        } 
    }
}
